<div class="row">
    <div class="col-lg-12">
        <h3 class="page-header">Nhập tích điểm</h3>
    </div>
    <!-- /.col-lg-12 -->
</div>
<div id="ajaxLoader-inner"></div>
<div class="row">
    <div class="col-lg-12">
        <div class="panel panel-default">
            <div class="panel-body">
                <div class="row">
                    <div class="col-lg-12">
                        <form role="form" method="POST" name="AddOrder" onsubmit="return checkinput();">                            
                            <div class="form-group">
                                <div class="row">
                                    <div class="col-lg-2">
                                        <label>Tỉnh thành</label>
                                        <a href="index.phtml"></a>
                                    </div>
                                    <div class="col-lg-2">
                                        <?php echo $this->provinceHTML ?>
                                    </div>
                                    <div class="col-lg-2">
                                        <label>Quận huyện</label>
                                    </div>
                                    <div class="col-lg-2">
                                        <?php echo $this->districtHTML ?>
                                    </div>




                                </div>
                            </div>                                       
                            <div class="form-group">
                                <div class="row">
                                    <div class="col-lg-2" >
                                        <label>D/S Đại lý</label>
                                    </div>
                                    <div class="col-lg-2" id="agent">
                                        <?php echo $this->agentHTML ?>
                                    </div>
                                    <div class="col-lg-2">
                                        <label>Ngày mua hàng</label>
                                    </div>
                                    <div class="col-lg-2">
                                        <input class="form-control" type="datetime" name="order_created" id="order_created" value="" >
                                    </div>




                                </div>
                            </div>
                            <div class="form-group">
                                <div class="row">
                                    <div class="col-lg-2">
                                        <label>D/S Sản phẩm</label>
                                    </div>
                                    <div class="col-lg-2">
                                        <?php echo $this->productHTML ?>
                                    </div>
                                    <div class="col-lg-2">
                                        <label>Số lượng</label>
                                    </div>
                                    <div class="col-lg-2" id="quantity_id">
                                        <input id="quantity" class="form-control" name="quantity" onkeydown="change_text();" onkeyup="change_text();">
                                    </div>

                                </div>
                            </div>
                            <div class="form-group">
                                <div class="row">
                                    <div class="col-lg-2">
                                        <label>Hệ số điểm</label>
                                    </div>
                                    <div class="col-lg-2" id="factor_id">
                                        <input id="factor" class="form-control" name="factor" onkeydown="change_text();" onkeyup="change_text();" readonly="true">
                                    </div>
                                    <div class="col-lg-2">
                                        <label>Điểm nhận được</label>
                                    </div>
                                    <div class="col-lg-2" id="charges_id">
                                        <input id="charges" class="form-control" name="charges" readonly="true">
                                    </div>
                                </div>
                            </div>
                            <div class="form-group">
                                <button onclick="return add();" type="button" class="btn btn-primary">Thêm mới</button>
                                <button type="reset" class="btn btn-default">Đặt lại</button>
                                <button onclick="return $('#myModal').modal('show');" type="button" class="btn btn-default">Thêm đại lý mới</button>                                
                            </div> 
                            <div class="form-group">  
                                <table id="order_table" class="table tbale-reponsive table-hover">     
                                    <tr class="success">                                    
                                        <td>Đại lý</td>
                                        <td>Sản phẩm</td>
                                        <td>Hệ số điểm</td>
                                        <td>Số lượng</td> 
                                        <td>Điểm nhận được</td>
                                        <td>Ngày mua hàng</td>
                                        <td>Huỷ</td>
                                    </tr>
                                </table> 
                            </div>
                            <div class="form-group">
                                <button onclick="return addOrder();" type="button" class="btn btn-primary">Lưu đơn hàng</button>                                
                            </div>                                              

                        </form>

                    </div>
                </div>
            </div>
        </div>
    </div>   
</div>
<form  id="addAgent" method="POST" onsubmit="return checkAgent();">
    <div id="myModal" class="modal fade">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">
                        &times;</button>
                    <h4 class="modal-title">
                        <center>
                            Thêm đại lý mới
                        </center>
                    </h4>
                </div>
                <div class="modal-body">    

                    <div class="row">
                        <div class="col-lg-3">                            
                            Tên đại lý
                        </div>
                        <div class="col-lg-9">
                            <input class="form-control"  id="agent_name" name="oldpassword" /></div>
                    </div>

                    <div class="row">
                        <div class="col-lg-3">
                            Địa chỉ</div>
                        <div class="col-lg-9">
                            <input class="form-control"  id="agent_address" name="password" /></div>
                    </div>
                    <div class="row">
                        <div class="col-lg-3">
                            Khu vực</div>
                        <div class="col-lg-9">
                            <?php echo $this->popupareaHTML ?>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-lg-3">
                            Tỉnh thành</div>
                        <div class="col-lg-9">
                            <?php echo $this->popupprovinceHTML ?>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-lg-3">
                            Quận huyện</div>
                        <div class="col-lg-9">
                            <?php echo $this->popupdistrictHTML ?>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-lg-3">
                            Người đại diện</div>
                        <div class="col-lg-9">
                            <input class="form-control"  id="representavie" name="repassword" /></div>                       
                    </div>
                    <div class="row">
                        <div class="col-lg-3">
                            Số điện thoại</div>
                        <div class="col-lg-9">
                            <input class="form-control"  id="phone" name="repassword" /></div>                       
                    </div>
                    <div class="row">
                        <div class="col-lg-3">
                            Loại đại lý</div>
                        <div class="col-lg-9">
                            <?php echo GlobalLib::getCombo('agent_cat_id', 'agent_category', 'id', 'name', 0, false, '', null, 'class="form-control"') ?> 
                            <div class="col-lg-2">
                                <span style="color: Red;"></span></div>
                        </div>
                    </div>                    
                    <div class="modal-footer">    
                        <center>
                            <button  class="btn btn-primary" type="submit">
                                Thêm
                            </button>
                            <button type="button" id="close" class="btn btn-default" data-dismiss="modal">
                                Đóng
                            </button>
                        </center>
                    </div>
                </div>
            </div>
        </div>
</form>

<script type="text/javascript">
    $(document).ready(function () {
        $("#quantity").keydown(function (e) {
                    // Allow: backspace, delete, tab, escape, enter and .
                    if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 ||
                         // Allow: Ctrl+A
                        (e.keyCode == 65 && e.ctrlKey === true) || 
                         // Allow: home, end, left, right
                        (e.keyCode >= 35 && e.keyCode <= 39)) {
                             // let it happen, don't do anything
                             return;
                    }
                    // Ensure that it is a number and stop the keypress
                    if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
                        e.preventDefault();
                    }
                });
        $('#agent_id').multiselect({
            includeSelectAllOption:true,
            enableFiltering: true,
            maxHeight: '300',
            buttonWidth: '100%'
        });
        
        $("#order_created").datepicker({
            dateFormat: "dd-mm-yy",
            onSelect: function () {
                var params = {
                    action: 'getproduct',
                    agent_id: $('#agent_id').val(),
                    product_id: $('#product_id').val(),
                    order_created: $('#order_created').val()
                };
                $.post('<?php echo $this->baseUrl() ?>/default/service/index', params,
                        function (data) {
                            var items = eval(data);
                            var jItem = items[0];
                            $('#product_id').html(jItem.html);
                            $('#charges_id').html(jItem.html3);
                            $('#factor_id').html(jItem.html1);
                            $('#quantity_id').html(jItem.html2);
                        });
            }
        });

        $("#province_id").change(function () {
            var param =
                    {
                        province_id: $("#province_id").val()
                    };
            $.post("<?php echo $this->baseUrl() . "/default/order/getareafromprovince" ?>", param, function (data) {
                $("#popup_area_id").val(parseInt(data));
                var paramprovince =
                        {
                            area_id: parseInt(data)
                        };
                $.post("<?php echo $this->baseUrl() . "/default/order/getlistprovincefromarea" ?>", paramprovince, function (dataprovince) {
                    $("#popup_province_id").replaceWith(dataprovince);
                    $("#popup_province_id").val($("#province_id").val());
                    var paramdistrict =
                            {
                                province_id: $("#popup_province_id").val()
                            };
                    $.post("<?php echo $this->baseUrl() . "/default/order/getlistdistrictfromprovince" ?>", paramdistrict, function (datadistrict) {
                        $("#popup_district_id").replaceWith(datadistrict);
                    });
                });
            });
        });
        $("#district_id").change(function () {
            $("#popup_district_id").val($("#district_id").val());
        });

    });
    function change_text()
    {
        var quantity = $('#quantity').val();
        var factor = $('#factor').val();
        var charges = quantity * factor;
        var n = parseFloat(charges);
        x = Math.round(n * 1000) / 1000;
        document.getElementById('charges').value = x;
    }
    ;
    function checkAgent()
    {
        if ($("#agent_name").val() === "") {
            bootbox.alert("Vui lòng nhập tên của đại lý");
            return false;
        }
        ;
        var paramss =
                {
                    name: $("#agent_name").val(),
                    address: $("#agent_address").val(),
                    area_id: $("#popup_area_id").val(),
                    province_id: $("#popup_province_id").val(),
                    district_id: $("#popup_district_id").val(),
                    representavie: $("#representavie").val(),
                    phone: $("#phone").val(),
                    agent_cat_id: $("#agent_cat_id").val()
                };

        $.post('<?php echo $this->baseUrl() . "/default/order/addagent" ?>', paramss, function (data) {
            $('#myModal').modal('hide');
            $("#agent_id").append("<option value='" + data + "' selected='selected'>" + $("#agent_name").val() + "</option>");
        });
        event.preventDefault();
    }
    ;


</script>
<script type="text/javascript">
    function deleteline(line)
    {
        var x = document.getElementById("line" + line);
        x.remove();
    }
    
    $("#district_id").change(function () {
        if ($("#districy_id").val() == "0")
            getAgentAndDistrict("<?php echo $this->baseUrl() . '/' ?>");
    });
</script>
<script type="text/javascript">
    document.forms['AddOrder'].name.focus();
    function set_focus() {
        document.forms['AddOrder'].name.focus();
    }
    function add() {
        if ($("#agent_id").val() == "0")
        {
            bootbox.alert("Vui lòng chọn đại lý");
            return false;
        }
        if ($("#order_created").val() == "")
        {
            bootbox.alert("Vui lòng chọn ngày mua hàng");
            return false;
        }
        if ($("#product_id").val() == "0")
        {
            bootbox.alert("Vui lòng chọn sản phẩm");
            return false;
        }
        if ($("#factor").val() == "")
        {
            bootbox.alert("Sản phẩm này chưa được thiết lập hệ số điểm");
            return false;
        }
        if ($("#quantity").val() == "" || isNaN($("#quantity").val()) == true)
        {
            bootbox.alert("Vui lòng nhập số lượng");
            return false;
        }
        var exist = true;
        for (var i = 1; i <= document.getElementById("order_table").rows.length - 1; i++)
        {
            if ($("#agent" + i).val() == $("#agent_id").val() && $("#product" + i).val() == $("#product_id").val()
                    && $("#order_created").val() == $("#order_created" + i).val())
            {
                $("#quantity" + i).val(parseInt($("#quantity" + i).val()) + parseInt($("#quantity").val()));
                $("#charges" + i).val(parseInt($("#charges" + i).val()) + parseInt($("#charges").val()));
                document.getElementById("p_quantity" + i).innerHTML = $("#quantity" + i).val().toString();
                document.getElementById("p_charges" + i).innerHTML = $("#charges" + i).val().toString();
                exist = false;
                break;
            }
        }
        if (exist)
        {
            document.getElementById("order_table").innerHTML =
                    document.getElementById("order_table").innerHTML
                    + "<tr id='line" + document.getElementById("order_table").rows.length + "' class='info'>"
                    + "<td ><input id='agent" + document.getElementById("order_table").rows.length + "' type='hidden' value='" + $("#agent_id").val() + "'>" + $("#agent_id option:selected").text() + "</td>"
                    + "<td ><input id='product" + document.getElementById("order_table").rows.length + "' type='hidden' value='" + $("#product_id").val() + "'>" + $("#product_id option:selected").text() + "</td>"
                    + "<td ><input id='factor" + document.getElementById("order_table").rows.length + "' type='hidden' value='" + $("#factor").val() + "'>" + $("#factor").val() + "</td>"
                    + "<td ><input id='quantity" + document.getElementById("order_table").rows.length + "' type='hidden' value='" + $("#quantity").val() + "'><p id='p_quantity" + document.getElementById("order_table").rows.length + "'>" + $("#quantity").val() + "</p></td>"
                    + "<td ><input id='charges" + document.getElementById("order_table").rows.length + "' type='hidden' value='" + $("#charges").val() + "'><p id='p_charges" + document.getElementById("order_table").rows.length + "'>" + $("#charges").val() + "</p></td>"
                    + "<td ><input id='order_created" + document.getElementById("order_table").rows.length + "' type='hidden' value='" + $("#order_created").val() + "'><p id='p_order_created" + document.getElementById("order_table").rows.length + "'>" + $("#order_created").val() + "</p></td>"
                    + "<td><a onclick='return $(\"#line" + document.getElementById("order_table").rows.length + "\").remove();' class='fa fa-trash-o  fa-lg' href='#'></a></td>"
                    + "</tr>";
        }
        $("#area_id").hide();
//        $("#agent_id").val(0);
        $("#product_id").val(0);
        $("#factor").val("");
        $("#quantity").val("");
        $("#charges").val("");
        
    }
    ;
</script>
<script type="text/javascript">
    
    function addOrder()
    {
        if (document.getElementById("order_table").rows.length - 1 == 0)
        {
            bootbox.alert("Chưa có sản phẩm nào được chọn!");
            return false;
        }
        var totalcharges = 0;
        for (var i = 1; i <= document.getElementById("order_table").rows.length - 1; i++)
        {
            totalcharges = totalcharges + parseInt($("#charges" + i).val());
        }
        var param = {
            charges: totalcharges
        };
        var flag=0;
         $.ajax({
            url: "<?php echo $this->baseUrl()?>/default/order/addorder",
            type: 'POST',
            async:false,
            data: param,
            beforeSend:function(){
                 $('html').addClass('ajaxLoader-inner');
            },
            success: function(data) {
                
                flag=flag+1;
                for (var i = 1; i <= document.getElementById("order_table").rows.length - 1; i++){
                    var params = {
                        order_no: data.trim(),
                        product_id: $("#product" + i).val(),
                        quantity: $("#quantity" + i).val(),
                        agent_id: $("#agent" + i).val(),
                        factor: $("#factor" + i).val(),
                        charges: $("#charges" + i).val(),
                        order_created: $("#order_created" + i).val()
                    };
                        $.ajax({
                           url: "<?php echo $this->baseUrl() ?>/default/order/adddetail",
                           type: 'POST',
                           async:false,
                           data: params,
                           success: function(data) {
                              flag=flag+1;
                           } 
                       });
                }
            } 
        });
        if(flag==document.getElementById("order_table").rows.length){
            window.location = "<?php echo $this->baseUrl() . '/default/order/list' ?>";
        }
    }
</script>